import glob
import os
import cv2
from PIL import Image

new_count = 0


def img_compress(path, size, quality):
    image = Image.open(path)
    width, height = image.size
    new_width = int(width * size)
    new_height = int(height * size)
    resized_image = image.resize((new_width, new_height))
    # 获取图片将要保存的文件夹路径和文件名
    new_path = get_new_path(path)
    # 修改图片格式 为了能用jpg保存
    resized_image = resized_image.convert('RGB')
    # 修改后缀为jpg
    suffix = path.split('.')[-1]
    path = path.replace(suffix, '')

    resized_image.save(new_path, quality=quality, format="JPEG")


# 压缩视频
def compress_video(input_path, output_path, scale_percent=50, fps=30):
    video = cv2.VideoCapture(input_path)
    width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH) * scale_percent / 100)
    height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT) * scale_percent / 100)
    codec = cv2.VideoWriter_fourcc(*"mp4v")
    output = cv2.VideoWriter(output_path, codec, fps, (width, height))

    while True:
        ret, frame = video.read()
        if not ret:
            break
        resized_frame = cv2.resize(frame, (width, height))
        output.write(resized_frame)

    video.release()
    output.release()


# 生成新的文件地址
def get_new_path(path):
    new_path = f'./new/{path[1:]}'
    directory, filename = os.path.split(new_path)
    # 如果文件夹不存在，则创建它
    if not os.path.exists(directory):
        os.makedirs(directory)
    return new_path


def traverse_folder(folder_path):
    file_paths = glob.glob(folder_path + '/**', recursive=True)
    res = []
    for file_path in file_paths:
        if os.path.isfile(file_path):
            print(file_path)
            res.append(file_path)
    return res


if __name__ == '__main__':
    image_suffix = ['jpg', 'tif', 'bmp', 'png', 'gif']
    video_suffix = ['avi', 'wmv', 'mpg', 'mpeg', 'mov', 'mp4']
    size = 0.5
    quality = 50
    # img_compress('15F_FE_O.BMP', size, quality)
    all_paths = traverse_folder('./')
    for path in all_paths:
        suffix = path.split('.')[-1]
        # 判断该文件是否是图片
        # if suffix in image_suffix:
        #     img_compress(path, size, quality)
        if suffix in video_suffix:
            compress_video(path, get_new_path(path))
